package org.sang.service;

import org.sang.bean.Task;
import org.sang.common.DateConverter;
import org.sang.mapper.MemberMapper;
import org.sang.mapper.TaskMapper;
import org.sang.mapper.VolunteerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TaskService {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    VolunteerMapper volunteerMapper;

    public int addTask(Task task) {
        String memberName = task.getMemberName();
        String volunteerName = task.getVolunteerName();

        if (memberName!=null) {
            int memberNo = memberMapper.getNoByName(memberName);
            if (memberNo>0) {
                task.setMemberNo(memberNo);
            }
        }
        if (volunteerName!=null) {
            int volunteerNo = volunteerMapper.getNoByName(volunteerName);
            if (volunteerNo>0) {
                task.setMemberNo(volunteerNo);
            }
        }
        System.out.println("###here");

        return taskMapper.addTask(task);
    }

    public List<Task> getAll() {
        List<Task> tasks = taskMapper.getAll();
        for (Task task : tasks) {
            if (task.getExpectedEndTime() == null) {
                task.setStatusN(0);
            } else if (task.getEndTime() == null) {
                long diff = task.getExpectedEndTime().getTime() - task.getLaunchTime().getTime();
                Date current = new Date();
                double divide = 1.0 * (current.getTime() - task.getLaunchTime().getTime()) / diff;
                task.setStatusN((int) (divide * 100));
            } else {
                task.setStatusN(100);
            }

            if (task.getStatusN() < 0) {
                task.setStatusN(100);
            }
        }

        return tasks;
    }

    public int deleteTask(int taskNo) {
        return taskMapper.delete(taskNo);
    }

    public int updateTask(Task task) {
        return taskMapper.update(task);
    }

    public int updateTaskTime(Task task) {
        return taskMapper.updateTime(task);
    }

}
